package com.pig4cloud.pig.module.controller.promoter;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.promoter.PromoterSettlement;
import com.pig4cloud.pig.module.api.entity.promoter.PromoterUserRecord;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.promoter.IPromoterSettlementService;
import com.pig4cloud.pig.module.service.promoter.IPromoterUserRecordService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

/**
 * 推广员 邀请记录Controller
 *
 * @author ruoyi
 * @date 2022-11-11
 */
@Validated
@Api(value = "推广员 邀请记录控制器", tags = {"推广员 邀请记录管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/record")
public class PromoterUserRecordController {

    private final IPromoterUserRecordService promoterUserRecordService;
    private final IWxUserService wxUserService;
    private final IPromoterSettlementService promoterSettlementService;

    @Value("${ruoyi.imgUrl}")
    private String imgUrl;
    /**
     * 查询推广员 邀请记录列表
     */
    @ApiOperation("查询推广员 邀请记录列表")
    @PreAuthorize("@pms.hasPermission('module:record:list')")
    @GetMapping("/list")
    public TableDataInfo<PromoterUserRecord> list(@Validated PromoterUserRecord promoterUserRecord) {
        QueryWrapper<PromoterUserRecord> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(promoterUserRecord.getBeginDate())){
            qw.between("create_time", promoterUserRecord.getBeginDate() + " 00:00:00",promoterUserRecord.getEndDate() + " 23:59:59");
        }
        if (promoterUserRecord.getSettleId()!=null){
            qw.eq("settle_id",promoterUserRecord.getSettleId());
        }
        if (promoterUserRecord.getPromoterId()!=null){
            qw.eq("promoter_id",promoterUserRecord.getPromoterId());
        }
        if (promoterUserRecord.getState()!=null){
            qw.eq("state",promoterUserRecord.getState());
        }
		qw.orderByDesc("create_time");
        TableDataInfo<PromoterUserRecord> td = PageUtils.buildDataInfo(promoterUserRecordService.page(PageUtils.buildPage(),qw));
        List<PromoterUserRecord> list = td.getData();
        for (PromoterUserRecord list1:list){
            if (list1.getRegUserId()!=null){
                WxUser wxUser=wxUserService.findById(list1.getRegUserId());

				if(wxUser.getFaceUrl() != null){
					list1.setFaceUrl(wxUser.getFaceUrl());
					if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0) {
						list1.setFaceUrl(imgUrl + wxUser.getFaceUrl());
					}
				}
                try {
                    list1.setRegUserName(wxUser.getNickName());
                }catch (NullPointerException e){
                    list1.setRegUserName("微信用户");
                }

            }
            if(list1.getSettleId()!=null){
                PromoterSettlement promoter=promoterSettlementService.findById(list1.getSettleId());
                list1.setPromoterSettlement(promoter.getTradeNo());
            }
        }
        return td;
    }

    /**
     * 导出推广员 邀请记录列表
     */
    @ApiOperation("导出推广员 邀请记录列表")
    @PreAuthorize("@pms.hasPermission('module:record:export')")
    @SysLog("推广员 邀请记录")
    @GetMapping("/export")
    public List export(@Validated PromoterUserRecord promoterUserRecord) {
        QueryWrapper<PromoterUserRecord> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(promoterUserRecord.getBeginDate())){
            qw.between("create_time", promoterUserRecord.getBeginDate() + " 00:00:00",promoterUserRecord.getEndDate() + " 23:59:59");
        }
        if (promoterUserRecord.getSettleId()!=null){
            qw.eq("settle_id",promoterUserRecord.getSettleId());
        }
        if (promoterUserRecord.getPromoterId()!=null){
            qw.eq("promoter_id",promoterUserRecord.getPromoterId());
        }
        if (promoterUserRecord.getState()!=null){
            qw.eq("state",promoterUserRecord.getState());
        }
        qw.orderByDesc("create_time");
        List<PromoterUserRecord> list = promoterUserRecordService.list(qw);
        for (PromoterUserRecord list1:list){
            if (list1.getPromoterWxUserId()!=null){
                WxUser wxUser=wxUserService.findById(list1.getPromoterWxUserId());
                try {
                    list1.setPromoterName(wxUser.getNickName());
                }catch (NullPointerException e){
                    list1.setPromoterName("微信用户");
                }
            }
            if (list1.getRegUserId()!=null){
                WxUser wxUser=wxUserService.findById(list1.getRegUserId());
                try {
                    list1.setRegUserName(wxUser.getNickName());
                }catch (NullPointerException e){
                    list1.setRegUserName("微信用户");
                }
            }
            if (list1.getState()!=null){
                if (list1.getState()==0){
                    list1.setStates("未结算");
                }else if (list1.getState()==1){
                    list1.setStates("结算中");
                }else if (list1.getState()==2){
                    list1.setStates("已结算");
                }
            }
            if(list1.getAddSettleTime()!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                list1.setAddSettleTimes(sdf.format(list1.getAddSettleTime()));
            }
        }
        // ExcelUtil<PromoterUserRecord> util = new // ExcelUtil<PromoterUserRecord>(PromoterUserRecord.class);
        return  list;// util.exportExcel(list, "推广员 邀请记录");
    }

    /**
     * 获取推广员 邀请记录详细信息
     */
    @ApiOperation("获取推广员 邀请记录详细信息")
    @PreAuthorize("@pms.hasPermission('module:record:query')")
    @GetMapping("/{id}")
    public R<PromoterUserRecord> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        PromoterUserRecord promoterUserRecord = promoterUserRecordService.getById(id);
        return R.ok(promoterUserRecord);
    }

    /**
     * 新增推广员 邀请记录
     */
    @ApiOperation("新增推广员 邀请记录")
    @PreAuthorize("@pms.hasPermission('module:record:add')")
    @SysLog("推广员 邀请记录")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody PromoterUserRecord promoterUserRecord) {
        return R.okByRow(promoterUserRecordService.save(promoterUserRecord) ? 1 : 0);
    }

    /**
     * 修改推广员 邀请记录
     */
    @ApiOperation("修改推广员 邀请记录")
    @PreAuthorize("@pms.hasPermission('module:record:edit')")
    @SysLog("推广员 邀请记录")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody PromoterUserRecord promoterUserRecord) {
        return R.okByRow(promoterUserRecordService.updateById(promoterUserRecord) ? 1 : 0);
    }

    /**
     * 删除推广员 邀请记录
     */
    @ApiOperation("删除推广员 邀请记录")
    @PreAuthorize("@pms.hasPermission('module:record:remove')")
    @SysLog("推广员 邀请记录")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(promoterUserRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
